﻿using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OAuthApp.Data;
using OAuthApp.Services;
using Swashbuckle.AspNetCore.Annotations;

namespace OAuthApp.Apis
{
    [SwaggerTag("应用聊天室")]
    [ServiceFilter(typeof(ApiRequestLoggingAttribute))]
    public class AppChatMessagesController : BaseController
    {
        private readonly AppDbContext _context;

        public AppChatMessagesController(AppDbContext context)
        {
            _context = context;
        }

        [HttpGet]
        [SwaggerOperation(OperationId = "AppChatMessages")]
        public ActionResult List(long appId,int skip, int take)
        {
            var result = _context.AppChatMessages
                .Where(x => x.AppID == appId)
                .Skip(skip)
                .Take(take)
                .OrderByDescending(x => x.ID)
                .ToList();

            return OK(result);
        }

        [HttpGet("{id}")]
        [SwaggerOperation(OperationId = "AppChatMessage")]
        public ActionResult Get(long id)
        {
            var result = _context.AppChatMessages.Find(id);

            if (result == null)
            {
                return Error("消息不存在");
            }

            return OK(result);
        }

        [HttpPut("{id}")]
        [SwaggerOperation(OperationId = "AppChatMessagePut")]
        public ActionResult Put(AppChatMessage appChatMessage)
        {
            _context.Entry(appChatMessage).State = EntityState.Modified;

            try
            {
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }

            return OK(true);
        }

        [HttpPost]
        [SwaggerOperation(OperationId = "AppChatMessagePost")]
        public ActionResult Post(AppChatMessage appChatMessage)
        {
            _context.AppChatMessages.Add(appChatMessage);

            _context.SaveChanges();

            return OK(new { id = appChatMessage.ID });
        }

        [HttpDelete("{id}")]
        [SwaggerOperation(OperationId = "AppChatMessageDelete")]
        public ActionResult Delete(long id)
        {
            var result = _context.AppChatMessages.Find(id);

            if (result == null)
            {
                return Error("不存在的消息");
            }

            _context.AppChatMessages.Remove(result);

            _context.SaveChanges();

            return OK(true);
        }
    }
}
